package com.usts2022.classcostrecord;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.usts2022.classcostrecord.Utils.DateFormat;
import com.usts2022.classcostrecord.Utils.HttpUtils;
import com.usts2022.classcostrecord.entity.Report;
import com.usts2022.classcostrecord.entity.User;
import com.usts2022.classcostrecord.entity.UserViewModel;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ListFragment extends Fragment {
    private final static String TAG = "ListFragment";
    private RecyclerView mRecyclerView;
    private OrderListAdapter mAdapter;
    private List<Report> reports;
    private SwipeRefreshLayout swipeRefreshLayout;
    private UserViewModel userViewModel;
    private User user;
    private TextView itemIsOver;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //创建模型
        userViewModel = new ViewModelProvider(getActivity()).get(UserViewModel.class);
        reports = userViewModel.getReports();
        user = userViewModel.getUser();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_list, container, false);
        //绑定
        mRecyclerView = view.findViewById(R.id.list_item_xml);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new OrderListAdapter();
        mRecyclerView.setAdapter(mAdapter);

        //下拉刷新
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeLayout);
        swipeRefreshLayout.setColorSchemeResources(R.color.grey);
        swipeRefreshLayout.setSize(SwipeRefreshLayout.DEFAULT);
        swipeRefreshLayout.setProgressBackgroundColor(R.color.white);
        swipeRefreshLayout.setProgressViewEndTarget(true, 200);

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                try {
                    getReport(user.getClassCode());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                swipeRefreshLayout.setRefreshing(false);
            }
        });


        return view;
    }

    //adapter
    class OrderListAdapter extends RecyclerView.Adapter<OrderHolder> {

        @NonNull
        @Override
        public OrderHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
            return new OrderHolder(layoutInflater, parent);
        }

        @Override
        public void onBindViewHolder(@NonNull OrderHolder holder, int position) {
            Report report = reports.get(position);
            holder.setIsRecyclable(false);
            holder.band(report);
        }

        @Override
        public int getItemCount() {
            if (reports == null) {
                return 0;
            }
            return reports.size();
        }
    }

    class OrderHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        private Report mReport;
        private ImageView itemImg;
        private TextView itemCost, itemDate, itemPerson;

        public OrderHolder(LayoutInflater inflater, ViewGroup parent) {
            super(inflater.inflate(R.layout.list_item, parent, false));
            itemView.setOnClickListener(this);
            //绑定
            itemImg = itemView.findViewById(R.id.item_img);
            itemDate = itemView.findViewById(R.id.item_date);
            itemPerson = itemView.findViewById(R.id.item_person);
            itemCost = itemView.findViewById(R.id.item_cost);
            itemIsOver = itemView.findViewById(R.id.is_over);
        }

        //修改信息
        public void band(Report report) {
            this.mReport = report;
            itemCost.setText("金额: " + mReport.getCost().toString());
            itemPerson.setText("验收人: " + mReport.getAcceptancePerson());
            itemDate.setText("日期: " + DateFormat.dateToStr(mReport.getDate()));
            if (mReport.getIsOver() == 1) {
                itemIsOver.setText("状态: 已结束");
            } else {
                itemIsOver.setText("状态: 可质疑");
                if (DateFormat.timeAfterWeek(mReport.getDate())<(new Date().getTime())) {
                    new Thread() {
                        @Override
                        public void run() {
                            try {
                                HttpUtils.getNoTh("/user/changeReportStatus/"+mReport.getId());
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        itemIsOver.setText("状态: 已结束");
                                    }
                                });
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }.start();
                }
            }
            new Thread() {
                @Override
                public void run() {
                    String url = mReport.getItemPhoto();
                    try {
                        byte[] img = HttpUtils.getImg(url);
                        Message message = uiHandler.obtainMessage(1);
                        message.obj = img;
                        uiHandler.sendMessage(message);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }

        //点击事件
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getActivity(),ReportActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("report",mReport);
            bundle.putSerializable("user",user);
            intent.putExtras(bundle);
            startActivity(intent);
        }

        public Handler uiHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(@NonNull Message message) {
                if (message.what == 1) {
                    //通过message，拿到字节数组
                    byte[] picture = (byte[]) message.obj;
                    //使用BitmapFactory工厂，把字节数组转化为bitmap
                    Bitmap bitmap = BitmapFactory.decodeByteArray(picture, 0, picture.length);
                    //通过imageview，设置图片
                    itemImg.setImageBitmap(bitmap);
                    return true;
                }
                return false;
            }
        });
    }



    private void getReport(Integer classCode) throws IOException {
        String url = "/user/getReports/" + classCode;
        HttpUtils.get(url, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Looper.prepare();
                Looper.loop();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Looper.prepare();
                String str = response.body().string();
                if (response.code() != 200 || str.equals("")) {
                    Toast.makeText(getActivity(), "请登录", Toast.LENGTH_SHORT).show();
                    return;
                }
//                Message message = updateUI.obtainMessage(1);
//                message.obj = reports;
//                updateUI.sendMessage(message);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        List<Report> report = JSON.parseArray(str, Report.class);
                        userViewModel.setReports(report);
                        reports = userViewModel.getReports();
                        mAdapter.notifyDataSetChanged();
                    }
                });
                Looper.loop();
            }
        });
    }




}